<template>
  <section class="app-main">
    <div class="tabs-container">
      <div class="scroll-ico-container" @click.stop="goTabPreviousPage()">
        <i class="el-icon-arrow-left" :style="true === tabHavePreviousPage ? '' : 'color:#ddd'"/>
      </div>
      <div ref="tabListDiv" class="tab-list-container">
        <div
          v-for="(tabItem, tabIndex) in currentPageTabList"
          :key="tabItem.tabName"
          :ref="'tabItem' + tabItem.tabName"
          class="tab-item-container"
          :class="{'tab-active-container': tabItem.tabName === tabActiveIndexTabName}"
          @click="tabChangeHandle(tabIndex)"
          @click.middle="closeTabHandle(tabIndex)"
        >
          <svg-icon
            v-if="tabItem.tabName === tabActiveIndexTabName"
            icon-class="reload"
            class-name="tab-reload-button"
            :stroke="'#f07509'"
            @click.stop="reloadTabHandle(tabItem.tabName)"
          />
          <svg-icon
            v-if="tabItem.tabName !== tabActiveIndexTabName"
            icon-class="reload"
            class-name="tab-reload-space"
            style="visibility: hidden"
          />
          {{ tabItem.title || tabItem.meta.title }}
          <svg-icon
            v-if="!tabItem.disableDelete && tabList.length > 1"
            icon-class="close"
            class-name="tab-close-ico"
            :stroke="'#f07509'"
            @click.stop="closeTabHandle(tabIndex)"
          />
          <span v-if="tabItem.disableDelete || 1 === tabList.length" style="display:inline-block;width:3px"/>
        </div>
      </div>
      <div class="scroll-ico-container scroll-ico-container-border" @click.stop="goTabNextPage()">
        <i class="el-icon-arrow-right" :style="true === tabHaveNextPage ? '' : 'color:#ddd'"/>
      </div>
      <div
        class="scroll-ico-container scroll-ico-container-border"
        @click.stop="reloadTabHandle(tabActiveIndexTabName)"
      >
        <span class="el-dropdown-link">
          <svg-icon icon-class="reload"/>
        </span>
      </div>
      <div class="scroll-ico-container scroll-ico-container-border">
        <div v-if="1===tabList.length" class="el-dropdown-link" style="width:38px">
          <svg-icon icon-class="close" style="color:#ddd"/>
        </div>
        <el-dropdown v-if="1!==tabList.length" disabled @command="closeCommandHandle">
          <div class="el-dropdown-link" style="width:38px">
            <svg-icon icon-class="close"/>
          </div>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="closeCurrentHandle">关闭当前标签页</el-dropdown-item>
            <el-dropdown-item command="closeOtherHandle" @click="closeOtherHandle">关闭其他标签页</el-dropdown-item>
            <el-dropdown-item command="closeAllHandle" @click="closeAllHandle">关闭所有标签页</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
    </div>
    <div class="tabs-panner-container">
      <div
        v-for="tabItem in tabList"
        v-show="tabItem.tabName === tabActiveIndexTabName"
        :key="tabItem.tabName"
        class="tab-panner-item-container"
      >
        <!-- <keep-alive> -->
        <transition>
          <iframe
            :ref="tabItem.tabName || ''"
            :name="tabItem.tabName || ''"
            :src="'/#' + tabItem.path + (tabItem.params ? '?params=' + tabItem.params + '&time=' + new Date().getTime() + '&name=' + tabItem.tabName : '')"
            frameborder="0"
            :style="{width: '100%',height:'100%'}"
          />
        </transition>
        <!-- </keep-alive> -->
      </div>
    </div>
  </section>
</template>

<script>
import SvgIcon from '@/components/SvgIcon'
import store from "@/store";
// import iframeWindow from './iframeWindow'

let tabListDivWidth = 0

export default {
  name: 'AppMain',
  components: {
    SvgIcon
    // iframeWindow
  },
  props: {
    routes: {
      type: Array,
      required: true,
      default() {
        return []
      }
    },
    routeList: {
      type: Array,
      required: true,
      default() {
        return []
      }
    }
  },
  data() {
    return {
      tabActiveIndex: 0,
      currentPageTabActiveIndex: 0,
      tabActiveIndexTabName: '',
      tabList: [],
      currentPageTabList: [],
      pageDataNeedReload: [],
      tabPage: 1,
      tabHavePreviousPage: false,
      tabHaveNextPage: false
    }
  },
  computed: {
    // routeList: {
    //   get() {
    //     return this.routFlat(this.routes)
    //   }
    // }
  },
  watch: {
    tabActiveIndex: {
      handler() {
        this.$emit(
          'activeMenu',
          this.tabList[this.tabActiveIndex].permissionCode
        )
      }
    }
  },
  created() {
    this.init()
    this.addTabItem()
    this.receiveMsg()
    window.addEventListener('resize', this.handleResize)
    window.addEventListener('load', this.handleResize)
    window.getAndDeletePageDataNeedReload = (pageName) => {
      let needReload = false
      for (let i = 0; i < this.pageDataNeedReload.length; i++) {
        if (this.pageDataNeedReload[i] === pageName) {
          needReload = true
          this.pageDataNeedReload.splice(i--, 1)
        }
      }
      return needReload
    }
  },
  beforeDestroy: function () {
    window.removeEventListener('resize', this.handleResize)
    window.removeEventListener('load', this.handleResize)
  },
  methods: {
    handleResize() {
      if (undefined !== this.$refs.tabListDiv) {
        tabListDivWidth = this.$refs.tabListDiv.clientWidth
      }
      this.goTabPage()
    },
    goTabPage() {
      const pageList = [[]]
      let currentTabItemWidth
      let currentPageTabItemWidthSum = 0
      for (let i = 0; i < this.tabList.length; i++) {
        currentTabItemWidth = this.getTabItemWidth(this.tabList[i])
        if (currentPageTabItemWidthSum + currentTabItemWidth < tabListDivWidth) {
          // 当前页标签宽度加上新标签宽度小于总标签宽度，说明属于当前页
          currentPageTabItemWidthSum += currentTabItemWidth
          pageList[pageList.length - 1].push(this.tabList[i])
        } else {
          // 超过则往下一页
          pageList.push([this.tabList[i]])
          currentPageTabItemWidthSum = currentTabItemWidth
        }
      }
      this.currentPageTabList = pageList[this.tabPage - 1]
      // console.log('AAAAAAAAAAAAAAAAAAAAAAAAAAA', this.tabPage);
      this.tabHaveNextPage = this.tabPage < pageList.length
      this.tabHavePreviousPage = this.tabPage > 1
    },
    getTabItemWidth(tabItem) {
      // let tabItemDom;
      // tabItemDom = this.$refs['tabItem' + this.tabList[i].tabName];
      // if (undefined !== tabItemDom && tabItemDom.length > 0) {
      //     currentTabItemWidth = this.$refs['tabItem' + this.tabList[i].tabName][0].offsetWidth + 2;
      //     this.tabList[i].width = currentTabItemWidth;
      // } else {
      //     if (undefined !== this.tabList[i].width) {
      //         currentTabItemWidth = this.tabList[i].width;
      //     } else {
      //         currentTabItemWidth = 0;
      //     }
      // }
      // 除了标题文字以外的宽度
      let currentTabItemWidth = 74
      if (undefined !== tabItem.title && tabItem.title !== null) {
        currentTabItemWidth += this.$commonUtils.getSpaceQuantity(tabItem.title) * 7
      } else if (undefined !== tabItem.meta.title && tabItem.meta.title !== null) {
        currentTabItemWidth += this.$commonUtils.getSpaceQuantity(tabItem.meta.title) * 7
      } else {
        currentTabItemWidth += 1
      }
      return currentTabItemWidth
    },
    routFlat(routes) {
      let routeList = []
      routes.forEach((routeItem) => {
        if (routeItem.children && routeItem.children.length > 0) {
          routeList = routeList.concat(this.routFlat(routeItem.children))
        } else {
          routeList.push(routeItem)
        }
      })
      return routeList
    },
    init() {
      this.$nextTick(() => {
        if (undefined !== this.$refs.tabListDiv) {
          tabListDivWidth = this.$refs.tabListDiv.clientWidth
        }
      })
      let routeItem
      for (let i = 0; i < this.routes.length; i++) {
        routeItem = this.routes[i]
        if (routeItem.name === 'main') {
          this.tabList.push({...routeItem, tabName: new Date().getTime() + '_' + this.getRandom(6)})
          this.currentPageTabList = []
          this.currentPageTabList = [...this.tabList]
          this.tabActiveIndexTabName = this.tabList[this.tabActiveIndex].tabName
          break
        }
      }
      // 清除滚动条缓存
      localStorage.removeItem('pageScrollTopMap')
    },
    addTabItem() {
      this.$EventBus.$on('addTabItem', (route) => {
        this.$nextTick(() => {
          this.addTabHandle(route)
        })
      })
    },
    addTabHandle(route) {
      // console.log(route,this.routeList);
      const routeIndex = this.routeList.findIndex(res => res.name === route.name)
      if (routeIndex < 0) {
        console.log('暂无权限', route)
        return this.$message({type: 'warning', message: '暂无权限'})
      }
      const tabIndex = this.tabList.findIndex((res) => res.name === route.name)
      if (this.routeList[routeIndex].unique && tabIndex >= 0) {
        this.tabActiveIndex = tabIndex
        return
      }
      route = {
        ...this.routeList[routeIndex], ...route,
        tabName: new Date().getTime() + '_' + this.getRandom(6),
        params: route.params
      }
      if (route.path.substring(0, 1) !== '/') {
        route.path = '/' + route.path
      }
      delete route.children
      this.tabList.splice(this.tabActiveIndex + 1, 0, route)
      this.goTabPage()
      this.tabActiveIndex = this.tabActiveIndex + 1
      this.tabActiveIndexTabName = this.tabList[this.tabActiveIndex].tabName
      window.updateCurrentTabName(this.tabActiveIndexTabName)
      // 如果新添加的tab没有在当前页则翻到下一页
      let inCurrentPageTabList = false
      for (let i = 0; i < this.currentPageTabList.length; i++) {
        if (this.currentPageTabList[i].tabName === this.tabActiveIndexTabName) {
          inCurrentPageTabList = true
          break
        }
      }
      if (inCurrentPageTabList === false) {
        this.goTabNextPage()
      }
    },
    receiveMsg() {
      window.addEventListener('message', (event) => {
        let name2
        let index2
        switch (event.data.cmd) {
          case 'addTabItem':
            this.$localStorage.setItem('tempKey', JSON.stringify(event.data.params.params))
            this.addTabHandle(event.data.params)
            break
          case 'closeTabItem':
            this.closeCurrentHandle()
            break
          case 'getParams':
            name2 = event.source.name
            // console.log('event', event)
            index2 = this.tabList.findIndex(res => res.tabName === name2)
            // console.log('tabitem:', event.source.name2, this.tabList[index2].params)
            if (index2 >= 0) {
              this.$refs[name2][0].contentWindow.postMessage({
                cmd: 'sendParams',
                params: this.tabList[index2].params
              })
            }
            break
          case 'updateCurrentTabLabel':
            this.tabList[this.tabActiveIndex].title = event.data.params.title
            break
          case 'addPageDataNeedReload':
            this.pageDataNeedReload.push(event.data.params.pageName)
            break
          case 'hasNewVersion':
            store.dispatch('updateRouterMessage', {action: 'hasNewVersion'});
            break
          default:
            break
        }
      })
    },
    tabChangeHandle(tabIndex) {
      this.currentPageTabActiveIndex = tabIndex
      let tempTabIndex = tabIndex
      for (let i = 0; i < this.tabList.length; i++) {
        if (this.tabList[i].tabName === this.currentPageTabList[tabIndex].tabName) {
          tempTabIndex = i
          break
        }
      }
      this.tabActiveIndex = tempTabIndex
      this.tabActiveIndexTabName = this.tabList[this.tabActiveIndex].tabName
      window.updateCurrentTabName(this.tabActiveIndexTabName)
      if (undefined !== window.frames[this.tabActiveIndex]) {
        if (window.frames[this.tabActiveIndex].restoreScroll) {
          window.frames[this.tabActiveIndex].restoreScroll(this.tabActiveIndexTabName)
        }
        if (window.frames[this.tabActiveIndex].onShow) {
          window.frames[this.tabActiveIndex].onShow()
        }
      }
    },
    reloadTabHandle(tabName) {
      this.$refs[tabName][0].contentWindow.location.reload()
    },
    goTabPreviousPage() {
      if (this.tabHavePreviousPage === false) {
        return
      }
      this.tabPage = this.tabPage - 1
      this.goTabPage()
    },
    goTabNextPage() {
      if (this.tabHaveNextPage === false) {
        return
      }
      this.tabPage = this.tabPage + 1
      this.goTabPage()
    },
    closeTabHandle(tabIndex) {
      let tabIndexByList = 0
      for (let i = 0; i < this.tabList.length; i++) {
        if (this.currentPageTabList[tabIndex].tabName === this.tabList[i].tabName) {
          tabIndexByList = i
          break
        }
      }
      this.tabList.splice(tabIndexByList, 1)
      this.currentPageTabList.splice(tabIndex, 1)
      if (this.tabActiveIndex >= tabIndexByList) {
        this.tabActiveIndex = tabIndexByList - 1
      }
      if (this.tabActiveIndex < 0) {
        this.tabActiveIndex = this.tabList.length - 1
      }
      this.tabActiveIndexTabName = this.tabList[this.tabActiveIndex].tabName
      // 重新计算和更新当前tabItem
      this.goTabPage()
      // 如果当前的tab没有在当前页则翻到上一页
      let inCurrentPageTabList = false
      if (undefined !== this.currentPageTabList) {
        for (let i = 0; i < this.currentPageTabList.length; i++) {
          if (this.currentPageTabList[i].tabName === this.tabActiveIndexTabName) {
            inCurrentPageTabList = true
            break
          }
        }
      }
      if (inCurrentPageTabList === false) {
        this.goTabPreviousPage()
      }
      if (undefined !== window.frames[this.tabActiveIndex] && window.frames[this.tabActiveIndex].onShow) {
        window.frames[this.tabActiveIndex].onShow()
      }
    },
    closeCurrentHandle() {
      let tabIndexByList = 0
      for (let i = 0; i < this.currentPageTabList.length; i++) {
        if (this.currentPageTabList[i].tabName === this.tabList[this.tabActiveIndex].tabName) {
          tabIndexByList = i
          break
        }
      }
      this.closeTabHandle(tabIndexByList)
    },
    closeOtherHandle() {
      const tabItem = this.tabList[this.tabActiveIndex]
      this.tabList = [tabItem]
      this.currentPageTabList = []
      this.currentPageTabList = [...this.tabList]
      this.tabActiveIndex = 0
      this.tabActiveIndexTabName = this.tabList[this.tabActiveIndex].tabName
      // 重新计算和更新当前tabItem
      this.tabPage = 1
      this.goTabPage()
    },
    closeAllHandle() {
      this.tabList = []
      this.currentPageTabList = []
      this.tabActiveIndex = 0
      this.tabActiveIndexTabName = ''
      this.init()
      // 重新计算和更新当前tabItem
      this.tabPage = 1
      this.goTabPage()
    },
    closeCommandHandle(command) {
      this[command]()
    },
    getRandom(n) {
      if (n > 21) return null
      return parseInt((Math.random() + 1) * Math.pow(10, n - 1))
    }
  }
}
</script>

<style lang="scss" scoped>
@import "~@/styles/variables.scss";

.app-main {
  /*50 = navbar  */
  height: calc(100vh - 50px);
  width: 100%;
  position: relative;
  overflow: hidden;
}

.fixed-header + .app-main {
  padding-top: 50px;
}

.tab-reload-button {
  position: relative;
  top: 2px;
  font-size: 20px;
  color: #000000;
  visibility: hidden;
  left: 0;
  margin-left: -16px;
  margin-right: 0;
}

.tab-reload-space {
  position: relative;
  top: 2px;
  font-size: 20px;
  color: #000000;
  visibility: hidden;
  margin-left: -16px;
  margin-right: 0;
}

.tabs-container {
  height: 40px;
  width: 100%;
  border-bottom: 1px solid #eaeaea;
  display: flex;
  overflow-y: hidden;

  .scroll-ico-container {
    width: 40px;
    height: 40px;
    text-align: center;
    line-height: 40px;
    cursor: pointer;

    .double-left {
      color: red;
      background-color: red;
      width: 200px;
    }
  }

  .scroll-ico-container-border {
    border-left: 1px solid #eaeaea;
  }

  .tab-list-container {
    width: calc(100% - 80px);
    overflow-x: auto;
    height: 40px;
    white-space: nowrap;
    display: flex;
    overflow-y: hidden;

    .tab-item-container {
      height: 100%;
      line-height: 40px;
      font-size: 14px;
      color: #606266;
      padding: 0 20px;
      border-left: 1px solid #eaeaea;
      position: relative;
      display: inline-block;
      cursor: pointer;
      user-select: none;

      .tab-close-ico {
        vertical-align: middle;
        margin-left: 6px;
      }

      .tab-close-ico:hover {
        background-color: red;
        border-radius: 50%;
        color: #ffffff;
      }
    }

    .tab-item-container:last-child {
      border-right: 1px solid #eaeaea;
    }

    .tab-item-container:hover {
      color: #f07509;

      .tab-close-ico {
        color: #606266;
      }

      .tab-close-ico:hover {
        color: #ffffff;
      }

      .tab-reload-button {
        visibility: visible;
      }
    }

    .tab-item-container:hover:before,
    .tab-active-container:before {
      content: "";
      position: absolute;
      top: 0;
      left: 0;
      height: 2px;
      width: 100%;
      background: #f07509;
    }

    .tab-active-container {
      background: rgb(228, 226, 226, 0.2);
    }
  }
}

.tabs-panner-container {
  width: 100%;
  height: calc(100% - 40px);

  .tab-panner-item-container {
    width: 100%;
    height: 100%;
    overflow: hidden;
  }
}
</style>

<style lang="scss">
// fix css style bug in open el-dialog
.el-popup-parent--hidden {
  .fixed-header {
    padding-right: 15px;
  }
}
</style>
